존재하지 않는 속성에 접근할 때 발생한다.
class Sample:
pass
obj = Sample()
print(obj.value) # AttributeError: 'Sample' object has no attribute 'value'
모듈을 불러올 때 발생한다.
import nonexistent_module # ImportError: No module named 'nonexistent_module'
리스트 또는 튜플에서 잘못된 인덱스에 접근할 때 발생한다.
my_list = [1, 2, 3]
print(my_list[5]) # IndexError: list index out of range
존재하지 않는 딕셔너리 키를 사용할 때 발생한다.
my_dict = {"name": "Kim"}
print(my_dict["age"]) # KeyError: 'age'
정의되지 않은 변수를 사용할 때 발생한다.
print(x) # NameError: name 'x' is not defined
잘못된 문법을 사용할 때 발생한다.
# SyntaxError 예제 (잘못된 문법)
# 실행 시 오류 발생
print("Hello" # 닫는 괄호 누락
잘못된 타입 연산을 수행할 때 발생한다.
result = "Hello" + 5 # TypeError: can only concatenate str (not "int") to str
부적절한 값을 사용할 때 발생한다.
int("Hello") # ValueError: invalid literal for int() with base 10
0으로 나누기를 수행할 때 발생한다.
x = 1 / 0 # ZeroDivisionError: division by zero
Python에서는 try-except
블록을 사용하여 예외를 처리할 수 있다.
try:
x = 1 / 0 # ZeroDivisionError 발생
except ZeroDivisionError:
print("0으로 나눌 수 없습니다.")
finally:
print("이 코드는 항상 실행된다.")
사용자가 직접 예외를 정의할 수 있다.
class CustomError(Exception):
def __init__(self, message):
self.message = message
super().__init__(self.message)
try:
raise CustomError("이것은 사용자 정의 예외입니다.")
except CustomError as e:
print(f"오류 발생: {e}")